﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Controls;

namespace WebFlipScreenSaver.Controls
{
	public static partial class WebBroswerExtensions
	{
		static readonly Guid SID_SWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");

		static Guid _serviceGuid = SID_SWebBrowserApp;

		static Guid _iid = typeof(IWebBrowser2).GUID;

		public static void PageZoom(this WebBrowser webBrowser, double zoom)
		{
			// For this code to work: add the Microsoft.mshtml .NET reference       
			mshtml.IHTMLDocument2 doc = webBrowser.Document as mshtml.IHTMLDocument2;
			doc.parentWindow.execScript("document.body.style.zoom=" + zoom.ToString().Replace(",", ".") + ";");
		}

		public static void OpticalZoom(this WebBrowser webBrowser, int amt)
		{
			var myWebBrowser2 = webBrowser.GetIWebBrowser2();
			if (myWebBrowser2 != null)
			{
				object pvaIn = amt;
				myWebBrowser2.ExecWB(OLECMDID.OLECMDID_OPTICAL_ZOOM, OLECMDEXECOPT.OLECMDEXECOPT_DONTPROMPTUSER, ref pvaIn, IntPtr.Zero);
			}

		}

		public static IWebBrowser2 GetIWebBrowser2(this WebBrowser webBrowser)
		{
			if (webBrowser != null)
			{
				var serviceProvider = (IServiceProvider)webBrowser.Document;
				if(serviceProvider != null)
				{
					var wb = (IWebBrowser2)serviceProvider.QueryService(ref _serviceGuid, ref _iid);

					return wb;
				}
					
			}
			return null;

		}

		public static void SuppressScriptErrors(this WebBrowser webBrowser, bool hide)
		{
			FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
			if (fiComWebBrowser == null)
				return;
			object objComWebBrowser = fiComWebBrowser.GetValue(webBrowser);
			if (objComWebBrowser == null)
				return;

			objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
		}



	} 

}
